package com.example.yuecvideo.utils;


import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

public class ImageSaveUtil {

    public static File Save(ContentResolver resolver, String imageUri, int width, int height) throws IOException {
        Log.i("width", ""+width);
        Log.i("height", ""+height);
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(imageUri));
        Mat src = MatUtil.bitmapToMap(bitmap);
        Mat dst = new Mat();
        Size size = new Size(width, height);
        Imgproc.resize(src, dst, size);

        Bitmap newBitMap = Bitmap.createBitmap(dst.cols(), dst.rows(), Bitmap.Config.ARGB_8888);
        newBitMap = MatUtil.matToBitmap(dst);
        // 获取图片的Bitmap对象
        // 创建保存图片的文件
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;
        // 接着，将Bitmap保存到相册
        String[] info = imageUri.toString().split("/");
        String fileName = info[info.length - 1] + UUID.randomUUID().toString() + ".jpg"; // 文件名
        File file = new File(galleryPath + fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            newBitMap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i("保存文件", "成功");
        // 最后，更新相册
        return file;
    }
}
